<template>
  <div class="report-preview-page">
    <div v-if="loading" class="page-container">
      <div class="loading-wrapper">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
    </div>
    
    <div v-else-if="error" class="page-container">
      <div class="error-wrapper">
        <h1>预览失败</h1>
        <p>{{ error }}</p>
        <button @click="goBack" class="btn btn-primary">返回</button>
      </div>
    </div>
    
    <div v-else class="preview-container">
      <!-- 预览头部工具栏 -->
      <div class="preview-header">
        <div class="preview-header-content">
          <div class="preview-header-left">
            <h2>{{ reportTitle || '报表预览' }}</h2>
            <div class="preview-meta" v-if="fileInfo">
              <span class="meta-item">
                <span class="meta-label">文件类型：</span>
                <span class="meta-value">{{ fileInfo.file_type.toUpperCase() }}</span>
              </span>
              <span class="meta-item">
                <span class="meta-label">文件大小：</span>
                <span class="meta-value">{{ formatFileSize(fileInfo.file_size) }}</span>
              </span>
              <span class="meta-item" v-if="fileInfo.created_at">
                <span class="meta-label">创建时间：</span>
                <span class="meta-value">{{ formatDateTime(fileInfo.created_at) }}</span>
              </span>
            </div>
          </div>
          <div class="preview-header-right">
            <a
              v-if="fileInfo"
              :href="getDownloadUrl(runId, fileId)"
              class="btn btn-download"
              download
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                <polyline points="7 10 12 15 17 10"></polyline>
                <line x1="12" y1="15" x2="12" y2="3"></line>
              </svg>
              下载
            </a>
            <button @click="goBack" class="btn btn-secondary">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M19 12H5M12 19l-7-7 7-7"></path>
              </svg>
              返回
            </button>
          </div>
        </div>
      </div>
      
      <!-- 预览内容 -->
      <div class="preview-content">
        <iframe
          v-if="previewUrl"
          :src="previewUrl"
          frameborder="0"
          class="preview-iframe"
          @load="handleIframeLoad"
        ></iframe>
        <div v-else class="preview-error">
          <p>无法加载预览内容</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
// @ts-ignore
import api from '@/utils/api.js'
// @ts-ignore
import { createLogger } from '@/utils/logger.js'

const componentLogger = createLogger('ReportPreview')
const route = useRoute()
const router = useRouter()

const runId = ref(null)
const fileId = ref(null)
const loading = ref(true)
const error = ref(null)
const fileInfo = ref(null)
const reportData = ref({})
const previewUrl = ref('')

// 计算报表标题
const reportTitle = computed(() => {
  return reportData.value.title || reportData.value.template_name || '报表预览'
})

// 获取文件信息
const fetchFileInfo = async () => {
  try {
    // 获取运行详情
    const runResponse = await api.get(`/reports/runs/${runId.value}`)
    if (runResponse.data.success) {
      reportData.value = runResponse.data.data
      
      // 从文件列表中查找对应的文件
      if (reportData.value.files && reportData.value.files.length > 0) {
        const file = reportData.value.files.find(f => f.id === parseInt(fileId.value))
        if (file) {
          fileInfo.value = file
          // 构建预览URL（使用后端API）
          previewUrl.value = `/api/reports/runs/${runId.value}/files/${fileId.value}/preview`
        } else {
          error.value = '文件不存在'
        }
      } else {
        error.value = '未找到文件列表'
      }
    } else {
      error.value = runResponse.data.message || '加载失败'
    }
  } catch (err) {
    componentLogger.error('获取文件信息失败', err)
    error.value = err.response?.data?.message || err.message || '加载失败'
  } finally {
    loading.value = false
  }
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  let fileSize = Number(size)
  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024
    index++
  }
  return `${fileSize.toFixed(2)} ${units[index]}`
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  try {
    let date
    if (typeof dateTime === 'string') {
      if (dateTime.includes('GMT') || dateTime.includes('UTC')) {
        date = new Date(dateTime)
      } else if (dateTime.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/)) {
        return dateTime
      } else {
        date = new Date(dateTime)
      }
    } else if (dateTime instanceof Date) {
      date = dateTime
    } else {
      return String(dateTime)
    }
    
    if (isNaN(date.getTime())) {
      return String(dateTime)
    }
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (err) {
    return String(dateTime)
  }
}

// 获取下载URL
const getDownloadUrl = (runId, fileId) => {
  return `/api/reports/runs/${runId}/files/${fileId}/download`
}

// 返回
const goBack = () => {
  // 如果是从分享页面打开的，返回分享页面；否则返回首页
  if (document.referrer && document.referrer.includes('/reports/share/')) {
    window.history.back()
  } else {
    window.location.href = `/#/reports/share/${runId.value}`
  }
}

// iframe加载完成
const handleIframeLoad = () => {
  componentLogger.info('预览内容加载完成')
}

onMounted(() => {
  runId.value = route.params.runId
  fileId.value = route.params.fileId
  
  if (runId.value && fileId.value) {
    fetchFileInfo()
  } else {
    error.value = '缺少必要参数'
    loading.value = false
  }
})
</script>

<style>
/* 全局样式 - 确保预览页面全屏独立显示 */
.report-preview-page {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  min-height: 100vh;
  background: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  overflow: hidden;
  z-index: 9999;
  margin: 0;
  box-sizing: border-box;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-wrapper,
.error-wrapper {
  background: white;
  border-radius: 12px;
  padding: 60px;
  box-shadow: 0 10px 40px rgba(0,0,0,0.2);
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-wrapper h1 {
  color: #dc3545;
  margin-bottom: 10px;
  font-size: 24px;
}

.error-wrapper p {
  color: #666;
  margin-bottom: 20px;
}

.preview-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: white;
}

.preview-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  z-index: 10;
}

.preview-header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px 24px;
  max-width: 100%;
}

.preview-header-left {
  flex: 1;
  min-width: 0;
}

.preview-header-left h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.preview-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  font-size: 13px;
  opacity: 0.95;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.meta-label {
  opacity: 0.8;
}

.meta-value {
  font-weight: 500;
}

.preview-header-right {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
  margin-left: 20px;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 10px 18px;
  border-radius: 8px;
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  border: none;
  transition: all 0.3s;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  border-color: rgba(255, 255, 255, 0.5);
}

.btn:active {
  transform: translateY(0);
}

.btn svg {
  width: 16px;
  height: 16px;
  stroke-width: 2.5;
}

.btn-download {
  background: rgba(255, 255, 255, 0.25);
}

.btn-download:hover {
  background: rgba(255, 255, 255, 0.35);
}

.btn-secondary {
  background: rgba(255, 255, 255, 0.15);
}

.preview-content {
  flex: 1;
  overflow: hidden;
  background: #f5f5f5;
  position: relative;
}

.preview-iframe {
  width: 100%;
  height: 100%;
  border: none;
  background: white;
}

.preview-error {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .preview-header-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .preview-header-right {
    width: 100%;
    justify-content: flex-end;
    margin-left: 0;
  }
  
  .preview-meta {
    flex-direction: column;
    gap: 8px;
  }
  
  .btn {
    padding: 8px 14px;
    font-size: 13px;
  }
}
</style>
